/**
 * Created by billy on 2017/4/25.
 */
var g = require("nodeLib");
var fs = require("fs");
var formidable = require('formidable');
var _timeTool = require("../../utils/TimeTool");
var FileUpLoader = require(__utilspath("FileUpLoader"));
var _req = require("superagent");
var http = require("https");
var _basePath;
var _uploadOption;
var qs = require('querystring');

module.exports = class {
	constructor()
	{
		_basePath = g.data.const.get("uploadOption_basePath");
		_uploadOption = g.data.const.get("uploadOption_userAuth");
		_basePath = "upload/";
		_uploadOption = {"ext":[".jpg",".jpeg",".png"],"size":"3145728"};
//		var oss = {"region": "oss-cn-hangzhou","accessKeyId": "LTAIu7d1gYEyRCMK","accessKeySecret": "QZHnJtEdq4mYG3Xwz2ZJutjb0tCNmz","bucket": "bluesnail-test","basePath": ""}
//		this.file = new FileUpLoader(g.data.info.get("oss"), "oss");
//		this.file = new FileUpLoader(oss,"oss");
//		trace(g.data.info.get("oss"),"oss")
		this.add("uploadFile", this.upload);
		this.add("del", this.delete);
		this.add("req", this.req);
		this.add("upload", this.wxUpload);
	}

	upload($data, $success, $error, $client, $response)
	{
		if (!hasData($data, "type", "redirectUrl", "fileName"))
		{
			$error({code: 9999});
			return;
		}
		$data.fileName = $data.fileName.toLowerCase();
		var pathObj = g.path.parse($data.fileName);
		if (_uploadOption.ext.indexOf(pathObj.ext) < 0)
		{
			$error({"msg": "无效的文件包"});
			return;
		}

		var fileSize = parseInt($client.headers["content-length"]);
		if (_uploadOption.size != 0 && fileSize > _uploadOption.size)
		{
			var sizeLimit = (_uploadOption.size / 1048576).toFixed(2);
			$error("文件大小不能超过" + sizeLimit + "M");
			return;
		}

		var form = new formidable.IncomingForm({
			uploadDir: "./assets/upload",
			maxFieldsSize: _uploadOption.size,
			keepExtensions: true
		});

		form.parse($client, (err, fields, files)=>
		{
			if (err)
			{
				$error(err);
				return;
			}

			if (!files || !files.btn)
			{
				$error("file not found");
				return;
			}

			if (!fields)
			{
				$error("缺少必要的参数");
				return;
			}

			fileSize = files.btn.size;
			var filePath = files.btn.path;
			var filePathObj = g.path.parse(filePath);
			//	var fileName = g.md5(filePathObj.base).substring(8, 24);
			var fileName = filePathObj.base;
			filePath = "./assets/upload/" + fileName;
			fileName = fileName.replace("upload_", "");
			fileName = _timeTool.getDate() + "/" + fileName.substring(8, 24) + filePathObj.ext;
			var targetPath = _basePath + fileName;
//			$success("<script>alert(1)</script>", {"Content-Type": "text/html"}, "text", true);

			filePath = __projpath(filePath);
//			trace("filePath", filePath)
//			trace("targetPath", targetPath)
			this.file.upload(filePath, targetPath).then(($url)=>
			{
				var template = g.data.file.get("template");
				template.add(__projpath("./htmlTemplate/"))
				var html = template.get("uploadFile.html", {
					fileName: targetPath,
					size: fileSize,
					redirectUrl: $data.redirectUrl
				});
				$success(html, {"Content-Type": "text/html"}, "text", true);
				g.fs.unlink(filePath);
			}, ()=>
			{
				g.fs.unlink(filePath);
				$error("上传文件出错");
			});
		});
	}

	delete($data, $success, $error, $client, $response)
	{
		if (hasData($data, "fileName"))
		{
			var fileName = $data.fileName;
			this.file.delete(fileName);
			$success();
		}
		else
		{
			$error({code: 9999});
		}
	}

	delFile($fileName)
	{
		var dirPath = "./assets/upload/" + $fileName.split("/")[0];
		if (!fs.existsSync(dirPath))
		{
			return;
		}
		if (!fs.existsSync("./assets/upload/" + $fileName))
		{
			return;
		}
		fs.unlink("./assets/upload/" + $fileName, ()=>
		{
			if (g.file.getDirectoryListing(dirPath).length == 0)
			{
				fs.rmdir(dirPath);

			}
		});
	}

	rename($data, $success)
	{
		fs.rename($data.sourcePath, $data.targetPath, ()=>
		{
			var template = g.data.file.get("template");
			template.add(__projpath("./htmlTemplate"));
			var html = template.get("uploadFile.html", {
				fileName: $data.fileName,
				size: $data.fileSize,
				redirectUrl: $data.redirectUrl
			});
			$success(html, {"Content-Type": "text/html"}, "text", true);
		});
	}

	req($data, $success, $error, $client, $response)
	{
		var url = $client.url.replace("/file/req?", "");

		if (!url)
		{
			$error({code: 9999});
			return;
		}
		callReq(url).then(($data)=>
		{
// 			trace($data)
// 			var html = res.text;
			$success($data, {"Content-Type": "text/html"}, "text", true);
		})
	}

	wxUpload($data, $success, $error, $client, $response)
	{
		var chunks = [];
		var size = 0;
		var isInit = false;
		var fileType = "";
		$client.on('data', (chunk)=>
		{
			if (!isInit)
			{
				isInit = true;
				var str = chunk.toString().split("\r\n")[2];
				if (!str || str.indexOf("Content-Type") < 0 || (str.indexOf("image/jpg") < 0 && str.indexOf("image/jpeg") < 0 && str.indexOf("image/png") < 0))
				{
					$success("{\"code\":9999}", {"Content-Type": "text/html"}, "text", true);
					return;
				}

				if (str.indexOf("png") >= 0)
				{
					fileType = "png";
				}
				else
				{
					fileType = "jpg";
				}
			}
			chunks.push(chunk);
			size += chunk.length;
		});
		$client.on('end', ()=>
		{
			var data = null;
			switch (chunks.length)
			{
				case 0:
					data = new Buffer(0);
					break;
				case 1:
					data = chunks[0];
					break;
				default:
					data = new Buffer(size);
					for (var i = 0, pos = 0, l = chunks.length; i < l; i++)
					{
						var chunk = chunks[i];
						chunk.copy(data, pos);
						pos += chunk.length;
					}
					break;
			}

			var num = 0;
			var indexs = [];
			while (num < 4)
			{
				var index = data.indexOf("\r\n", indexs[indexs.length - 1] + 2);
				indexs.push(index);
				num += 1;
			}
			var lastIndex = data.lastIndexOf("\r\n", data.length - 3);
			index += 2;
			var contentBuf = data.slice(index, lastIndex);
			var fileName = _timeTool.getNowStamp(13) + (Math.random() + "").substr(3, 3);
			fileName = fileName + "." + fileType;
			var filePath = "./assets/upload/" + fileName;
			var targetPath = _basePath + fileName;
			g.fs.writeFileSync(__projpath(filePath), contentBuf);
			this.file.upload(filePath, targetPath).then(($url)=>
			{
				g.fs.unlink(filePath);
				$success(targetPath, {"Content-Type": "text/html"}, "text", true);
			}, ()=>
			{
				g.fs.unlink(filePath);
				$success("{\"code\": 8888}", {"Content-Type": "text/html"}, "text", true);
			});
		});
	}
}

function callReq($url)
{
	var promise = new Promise((resolved, reject)=>
	{
		var hostname = $url.split("//")[0] + "//" + $url.split("//")[1].split("/")[0];
		var path = $url.replace(hostname, "");
		var options = {
			hostname: hostname,
			port: 80,
			path: path,
			method: "GET",
			headers: {
				"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
				"Host": "api.map.baidu.com",
			}
		}

		http.get(options, (req, res)=>
		{
			var returnData = "";
			req.on('data', (data)=>
			{
				returnData += data;
			});
			req.on('end', ()=>
			{
				resolved(returnData)
			});
		});
	})

	return promise;
}